/**
 * StreamHttpClientGzipDemo.ino
 *
 *  Created on: 2023.7.7
 *
 */

#include <Arduino.h>

#define USE_SERIAL Serial


#include <Esp8266Gzip.h>
#include <Time.h>
#include <TimeLib.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#include <WiFiClient.h>

ESP8266WiFiMulti WiFiMulti;


void error(String msg) {
  USE_SERIAL.print("!!!ERROR:");
  USE_SERIAL.println(msg);
}


void setup() {

    WiFi.mode(WIFI_STA);
    WiFiMulti.addAP("SSID", "PASSWORD");

    USE_SERIAL.begin(115200);
    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

}


void loop() {
    // wait for WiFi connection
    uint8_t* buff = 0;
    int readed = 0;
    uint8_t *outbuf;
    {/**
     * @brief 
     * HTTPClient会消耗大量内存，特别是HTTPS，对于一些小内存的模块会报OOM异常
     * 所以需要用{}括起来让HTTPClient处理完以后释放内存，用于后边gzip解压
     */
      if ((WiFiMulti.run() == WL_CONNECTED)) {

        WiFiClient client;
        HTTPClient http;
        
        USE_SERIAL.print("[HTTP] begin...\n");
        // configure server and url
        http.begin(client, "http://192.168.0.3:8099/prosalon/?location=101270119&key=61xxxxx29430f81526xxxxxxx5ad9");
        // 接受Gzip
        http.addHeader("Accept-Encoding", "gzip");
        USE_SERIAL.print("[HTTP] GET...\n");
        // start connection and send HTTP header
        int httpCode = http.GET();
        if(httpCode > 0) {
            // HTTP header has been send and Server response header has been handled
            USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            int buflen = 512;
            if(httpCode == HTTP_CODE_OK) {
                  Serial.println("Code Ok");

                // get lenght of document (is -1 when Server sends no Content-Length header)
                int len = http.getSize();
                Serial.printf("len=%d\n",len);

                // create buffer for read
                // buf大小与接口相关，根据调用的接口自行调整
                buff = (uint8_t*)malloc(buflen);

                // get tcp stream
                WiFiClient * stream = http.getStreamPtr();
                Serial.println("stream Ok");
                // read all data from server
                while(http.connected() && (len > 0 || len == -1)) {
                    size_t size = stream->available(); // 还剩下多少数据没有读完？
                    USE_SERIAL.println(size);
                    if(size) {
                        // read up to 128 byte
                        size_t realsize=((size > buflen) ? buflen : size);
                        size_t readBytesSize = stream->readBytes(buff+readed, realsize);
                        if(len > 0) {
                            len -= readBytesSize;
                            readed += readBytesSize;
                        }
                        
                    } else {
                      USE_SERIAL.println("no avali size");
                    }
                    delay(1);
                }
                USE_SERIAL.println();
                USE_SERIAL.print("[HTTP] connection closed or file end.\n");

            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }
        http.end();
      }
    }
    if(readed>0) {
      //解压后的大小根据自身接口返回结果来确定
      outbuf=(uint8_t*)malloc(sizeof(uint8_t)*2048);
      uint32_t outprintsize=0;
      
      int result=Esp8266Gzip::decompress_gzip(buff, readed, outbuf, 2048,outprintsize);
      if(result>0) {
        USE_SERIAL.write(outbuf,outprintsize);
      }
      free(outbuf);
      outbuf = 0;
    }
    if(buff) {
      free(buff);
    }

    delay(10000);
}